#include "MWireframeBBoxObject.h"
#include "MMesh.h"
#include "MMaterialManager.h"
#include "MMeshManager.h"
#include "VertexST.h"
#include "VertexBuffer.h"
#include "IndexBuffer.h"

CMWireframeBBoxObject::CMWireframeBBoxObject( std::string& strName , CMSceneManager* pCreator ) :
CMSceneNode(strName , pCreator) , m_bUpdate(false) , m_pMesh(NULL)  
{ m_SceneNodeType = SC_TYPE_WIREFRAME_BOUNDINGBOX; 
  vec4 vcolor = vec4(1.0f,1.0f,0.0f,1.0f);
  SetVertexColor(vcolor);
}


CMWireframeBBoxObject::~CMWireframeBBoxObject(void)
{  m_pMesh->ReqRemoveMgr();
}


bool CMWireframeBBoxObject::Update(float fElapsedTime)
{  
   CMSceneNode::Update(fElapsedTime);
   
   if(!m_bUpdate)
   {
	   if(GetParent())
	   {  
		   std::string wirebox = GetName() + "_wireboxmesh";

		   if(CMMeshManager::GetSingletonPtr())
		   {  
			   if(m_pMesh.isNull())
			   {
                  CMMeshManager::ResourceCreateOrRetrieveResult res = CMMeshManager::GetSingletonPtr()->AddResource(const_cast<char*> (wirebox.c_str()),"");
			      m_pMesh = res.first; 
			   }
		   }
		   
		   CVertexBuffer<SLineVertex>*     pVertexBuffer  = new CVertexBuffer<SLineVertex>;
		   CIndexBuffer<unsigned short>*   pIndexBuffer   = new CIndexBuffer<unsigned short>;

		   MaterialPtr resMat; 
			   
		   if(CMMaterialManager::GetSingletonPtr())
		   { resMat = CMMaterialManager::GetSingletonPtr()->SearchResource("DEFAULTMAT");
		   } 

		   pIndexBuffer->SetPrimType(PF_LINELIST);
		   
		   for(int i = 0; i < 8 ; ++i)
		   {
			   SLineVertex v;
               v.m_p = GetParent()->GetWorldBoundingBoxPtr()->GetCorner(i);  
			   pVertexBuffer->Add(v);      
		   }
		   
		   pIndexBuffer->Add(0);
		   pIndexBuffer->Add(1);
		  		   
		   pIndexBuffer->Add(1);
		   pIndexBuffer->Add(3);
		   
		   pIndexBuffer->Add(3);
		   pIndexBuffer->Add(2);
		   		   
		   pIndexBuffer->Add(2);
		   pIndexBuffer->Add(0);

		   pIndexBuffer->Add(4);
		   pIndexBuffer->Add(5);
		   
		   pIndexBuffer->Add(5);
		   pIndexBuffer->Add(7);

		   pIndexBuffer->Add(7);
		   pIndexBuffer->Add(6);

		   pIndexBuffer->Add(6);
		   pIndexBuffer->Add(4);

		   pIndexBuffer->Add(0);
           pIndexBuffer->Add(4);  

		   pIndexBuffer->Add(1);
		   pIndexBuffer->Add(5);

		   pIndexBuffer->Add(2);
		   pIndexBuffer->Add(6);

		   pIndexBuffer->Add(3);
		   pIndexBuffer->Add(7);

		   m_pMesh->Load(pVertexBuffer,pIndexBuffer,resMat);
	   }

	   m_bUpdate = true;
   }

   return true;
}

bool CMWireframeBBoxObject::Render(IRenderSystem* pRenderingEngine)
{  CMSceneNode::Render(pRenderingEngine);

   if(m_pMesh.isNull())
   { m_pMesh->Render(pRenderingEngine);
   } 

   return true;
}